package boboUtil;

import java.util.ConcurrentModificationException;
import java.util.NoSuchElementException;

//基于双向链表实现的集合类，快速插入删除，可当做队列、栈、双端队列来用
public class BoboLinkedList<E> extends BoboAbstractSequentialList<E>
        implements BoboList<E>, BoboDeque<E>, java.io.Serializable{

    //内部类（结点），双向链表类（私有静态内部类）
    private static class Node<E>{
        E item;
        Node<E> prev;
        Node<E> next;

        Node( Node<E> prev,E element, Node<E> next) {
            this.prev = prev;
            this.item = element;
            this.next = next;
        }
    }

    //成员变量
    transient int size = 0;
    transient Node<E> first;
    transient Node<E> last;

    //构造函数
    public BoboLinkedList(){}
    public BoboLinkedList(BoboCollection<? extends E> c){
        this();
        addAll(c);
    }


    @Override
    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }

    private void checkElementIndex(int index) {
        if (!isElementIndex(index)){
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }
    }

    private boolean isElementIndex(int index){
        return index >= 0 && index < size;
    }

    @Override
    public E set(int index, E element) {
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldValue = x.item;
        x.item = element;
        return oldValue;
    }

    //链表尾部插入结点
    public boolean add(E e){
        linkLast(e);
        return true;
    }

    private void linkFirst(E e){
        final Node<E> f = first;
        final Node<E> newNode = new Node<E>(null, e, f);
        first = newNode;
        if (f == null){
            last = newNode;
        } else {
            f.prev = newNode;
        }

        size++;
        modCount++;
    }
    //链表尾部插入结点
    private void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<E>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;

        size++;
        modCount++;
    }

    //Inserts element e before non-null Node succ.
    void linkBefore(E e, Node<E> succ){
        Node<E> pred = succ.prev;
        Node<E> newNode = new Node<E>(pred, e, succ);
        if (pred == null){
            first = newNode;
        } else {
            pred.next = newNode;
        }
        succ.prev = newNode;

        size++;
        modCount++;
    }

    //删除非空结点x
    private E unlink(Node<E> x){
        final Node prev = x.prev;
        final Node next = x.next;
        final E oldValue = x.item;

        if (prev == null && next == null){
            first = last = null;
        } else if (next == null){
            last = prev;
            prev.next = null;
        } else if (prev == null){
            first = next;
            next.prev = null;
        } else {
            prev.next = next;
            next.prev = prev;
        }

        x.item = null;
        x.prev = null;
        x.next = null;

        size--;
        modCount++;
        return oldValue;
    }
    //删除并返回头结点的值
    private E unlinkFirst(Node<E> f){
        //已保证f是头结点，且f不为空
        final E element = f.item;
        final Node<E> next = f.next;

        f.item = null;
        f.next = null;  //help  GC

        first = next;
        if (next == null)
            last = null;
        else
            next.prev = null;

        size--;
        modCount++;

        return element;
    }

    //删除并返回尾结点的值
    private E unlinkLast(Node<E> l){
        //已经保证l是尾结点，且l不为空
        final E element = l.item;
        final Node<E> pred = l.prev;

        l.item = null;
        l.prev = null;      //help GC

        last = pred;
        if (pred == null)
            first = pred;
        else
            pred.next = null;

        size--;
        modCount++;

        return element;
    }
    @Override
    public void add(int index, E element) {
        checkPositionIndex(index);

        if (index == size){
            linkLast(element);
        } else {
            linkBefore(element, node(index));
        }
    }

    @Override
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }

    @Override
    public BoboList<E> subList(int fromIndex, int toIndex) {
        return null;
    }




    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean addAll(BoboCollection<? extends E> c) {
        return addAll(size, c);
    }

    //找到第index个结点
    Node<E> node(int index){
        if (index < (size >> 1)){
            Node<E> x = first;
            for (int i=0; i<index; i++){
                x = x.next;
            }
            return x;
        } else {
            Node<E> x = last;
            for (int i = size - 1; i > index; i--){
                x = x.prev;
            }
            return x;
        }
    }

    //追加指定BoboCollection中的元素至该链表
    @Override
    public boolean addAll(int index, BoboCollection<? extends E> c) {
        checkPositionIndex(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)    return false;

        Node<E> pred, succ;
        if (index == size){
            pred = last;
            succ = null;
        } else {
            succ = node(index);
            pred = succ.prev;
        }

        for (Object o : a){
            E e = (E) o;
            Node<E> newNode = new Node<E>(pred, e, null);
            if (pred == null){
                first = newNode;
            } else {
                pred.next = newNode;
            }
            pred = newNode;
        }

        if (succ == null){
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        modCount++;
        return true;
    }

    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index)){
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }
    }

    private boolean isPositionIndex(int index){
        return (index >= 0 && index <= size);
    }

    private String outOfBoundsMsg(int index){
        return "Index:" + index + ", Size:" + size;
    }
    @Override
    public void addFirst(E e) {
        linkFirst(e);
    }

    @Override
    public void addLast(E e) {
        linkLast(e);
    }

    //插入尾部
    @Override
    public boolean offer(E e) {
        return add(e);
    }

    @Override
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

    @Override
    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

    //删除头结点
    @Override
    public E remove() {
        return removeFirst();
    }

    @Override
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }

    @Override
    public E removeLast() {
        final Node<E> l = last;
        if (last == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }

    //删除并返回头结点的值，如果头结点为空，返回null
    @Override
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    //删除并返回头结点的值，如果头结点为空，返回null
    @Override
    public E pollFirst() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    @Override
    public E pollLast() {
        final Node<E> l = last;
        return (last == null) ? null : unlinkLast(l);
    }

    @Override
    public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }

    @Override
    public boolean removeLastOccurrence(Object o) {
        if (o == null){
            for (Node<E> x = last; x != null; x = x.prev){
                if (x.item == null){
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = last; x != null; x = x.prev) {
                if (o.equals(x)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

    @Override
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

    @Override
    public E peekFirst() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

    @Override
    public E peekLast() {
        final Node<E> l = last;
        return (l == null) ? null : l.item;
    }

    //返回头结点
    @Override
    public E element() {
        return getFirst();
    }

    @Override
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

    @Override
    public void push(E e) {
        addFirst(e);
    }

    @Override
    public E pop() {
        return removeFirst();
    }

    public BoboListIterator<E> listIterator(int index) {
        checkPositionIndex(index);
        return new ListItr(index);
    }

    private class ListItr implements BoboListIterator<E>{
        private Node<E> lastReturned;
        private Node<E> next;
        private int nextIndex;
        private int expectedModCount = modCount;

        ListItr(int index){
            //已经确保index在0-size范围内
            if (index == size){
                next = null;
            } else {
                next =  node(index);
            }

            nextIndex = index;
        }

        @Override
        public boolean hasNext() {
            return nextIndex < size;
        }

        @Override
        public E next() {
            checkForModification();
            if (!hasNext()){
                throw new NoSuchElementException();
            }
            lastReturned = next;
            next = next.next;
            nextIndex++;
            return lastReturned.item;
        }

        @Override
        public boolean hasPrevious() {
            return nextIndex > 0;
        }

        @Override
        public E previous() {
            checkForModification();
            if (!hasPrevious()){
                throw new NoSuchElementException();
            }

            lastReturned = next = (next == null) ?  last : next.prev;
            nextIndex--;
            return lastReturned.item;
        }

        @Override
        public int nextIndex() {
            return nextIndex;
        }

        @Override
        public int previousIndex() {
            return nextIndex - 1;
        }

        @Override
        public void remove() {
            checkForModification();
            if (lastReturned == null)
                throw new IllegalStateException();

            Node<E> lastNext = lastReturned.next;
            unlink(lastReturned);
            if (lastReturned == next)
                next = lastNext;
            else
                nextIndex++;

            lastReturned = null;
            expectedModCount++;
        }

        @Override
        public void set(E e) {
            if (next == null)
                throw new IllegalStateException();
            checkForModification();

            lastReturned.item = e;
        }

        @Override
        public void add(E e) {
            checkForModification();
            lastReturned = null;
            if (next == null)
                linkLast(e);
            else
                linkBefore(e, next);
            nextIndex++;
            expectedModCount++;
        }

        final void checkForModification(){
            if (expectedModCount != modCount)
                throw new ConcurrentModificationException();
        }
    }


}
